﻿using OA.IService;
using OA.Models;
using OA.Untils.Cache;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using System.Web.Caching;
using System.Web.Mvc;
using System.Web.Security;

namespace OA.UI.MVC.Filters
{
    public class OAAuthorizationFilterAttribute : FilterAttribute, IAuthorizationFilter
    {

        public ISysRoleService roleService { get; set; }

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            //判断当前action是否标注“AllowAnonymous”特性
            var attr= filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), false);
            if (attr.Length> 0)
            {
                return;
            }


            // 没有通过认证
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                filterContext.Result = new RedirectResult("/account");
                return;
            }
            // 通过认证，获取角色信息
            var identity=filterContext.HttpContext.User.Identity as FormsIdentity;
            var strRoles = identity.Ticket.UserData.Split(',');  //"1,2,3"
            List<SysAction> actions = new List<SysAction>();

            foreach (var id in strRoles)
            {
                List<SysAction> roleActions;
                bool useCache=true;
                try
                {
                    roleActions = MemcacheHelper.Get(id) as List<SysAction>;
                    useCache = false;
                }
                catch
                {
                    roleActions = filterContext.HttpContext.Cache[id] as List<SysAction>;
                }

                if (roleActions == null)
                {
                    var rid = int.Parse(id);
                    roleActions = roleService.GetList(r =>r.Id==rid).Include(r => r.Actions).FirstOrDefault().Actions.ToList();
                    if(useCache)
                        filterContext.HttpContext.Cache.Insert(id, roleActions, null,DateTime.Now.AddMinutes(3), Cache.NoSlidingExpiration);
                    else
                        MemcacheHelper.Set(id, roleActions,DateTime.Now.AddMinutes(3));
                }
                actions = actions.Union(roleActions).ToList();
            }
            
            //获取当前请求的action信息
            var controllname = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            var actionname = filterContext.ActionDescriptor.ActionName;
            var method = filterContext.HttpContext.Request.HttpMethod;

            // 判断当前action信息是否在用户拥有的权限集合中
            if(!actions.Any(a=>a.ControllerName.ToLower()==controllname.ToLower() 
                && a.ActionName.ToLower() ==actionname.ToLower() 
                && a.HttpMethod.ToLower() ==method.ToLower()))
            {
                filterContext.Result=new RedirectResult("/403.html");
            }


        }
    }
}